package AndroidHT.Workspace;

import java.net.Socket;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.util.Log;

public class HTService extends Service
{
private static final String TAG = "HTService";
private LocationManager mLocationManager = null;
private TelephonyManager mTelephoneManager = null;
private static final int LOCATION_INTERVAL = 10000;
private static final float LOCATION_DISTANCE = 5.0f;

private class LocationListener implements android.location.LocationListener{
    Location mLastLocation;
    String Imei;
    String Email;
    public LocationListener(String provider)
    {
        Log.e(TAG, "LocationListener " + provider);
        mLastLocation = new Location(provider);
    }
    public void onLocationChanged(Location location)
    {
        Log.e(TAG, "onLocationChanged: " + location);
        mLastLocation.set(location);        	  
   	  
   	  try
   	  {
   		  SharedPreferences settings = getSharedPreferences("HT",MODE_PRIVATE);
   		  if(settings.getString("HT_Start", "KO") == "OK")
   		  {
   			
	   		  Log.i(TAG,"Enviando datos a Server "+"190.18.128.130 : 5123");
	   		  Socket sock = new Socket("190.18.128.130",5123);
	   		 		  
	   		  String test = "{"
	   				  		+ "\"Id\":\""+"And4GPlay"+"\","
	   				  		+ "\"Lat\":\""+location.getLatitude()+"\","
	   				  		+ "\"Lng\":\""+location.getLongitude()+"\","
	   				  		+ "\"Alt\":\""+location.getAltitude()+"\","
	   				  		+ "\"Spe\":\""+location.getSpeed()+"\","						
	   				  		+ "\"IMEI\":\""+Imei+"\","
	   				  		+ "\"Mail\":\""+settings.getString("HT_Email","Not defined")+"\","
	   				  		+ "\"User\":\""+settings.getString("HT_User","Not defined")+"\","
	   				  		+ "\"Pass\":\""+settings.getString("HT_Password","Not defined")+"\""
	   		  				+ "}";
	   		  
	   		  Log.i(TAG,"Stream enviado: "+test);
	   		  
	   		  sock.getOutputStream().write(test.getBytes());
	   		  sock.close();
   		  
   		  }
   		  else
   		  {
   			  Log.i(TAG,"HT_Start es KO aun..");
   		  }
   	  }
   	  catch(Exception ex)
   	  {
   	      Log.e(TAG, "Error enviando al socket "+ex.getMessage());
   	  }
    }
    public void onProviderDisabled(String provider)
    {
        Log.e(TAG, "onProviderDisabled: " + provider);            
    }
    public void onProviderEnabled(String provider)
    {
        Log.e(TAG, "onProviderEnabled: " + provider);
    }
    public void onStatusChanged(String provider, int status, Bundle extras)
    {
        Log.e(TAG, "onStatusChanged: " + provider);
    }
} 
LocationListener[] mLocationListeners = new LocationListener[] {
        new LocationListener(LocationManager.GPS_PROVIDER),
        new LocationListener(LocationManager.NETWORK_PROVIDER)
};
@Override
public IBinder onBind(Intent arg0)
{
    return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{    
	Log.e(TAG, "onStartCommand");
    super.onStartCommand(intent, flags, startId);       
    return START_STICKY;
}
@Override
public void onCreate()
{

    Log.e(TAG, "onCreate");
    initializeLocationManager();
    try {
        mLocationManager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                mLocationListeners[1]);
        
        SharedPreferences settings = getSharedPreferences("HT",MODE_PRIVATE);
        
        mLocationListeners[1].Email = settings.getString("HT_Email","Not defined");
        mLocationListeners[1].Imei = mTelephoneManager.getDeviceId();
        
    } catch (java.lang.SecurityException ex) {
        Log.i(TAG, "fail to request location update, ignore", ex);
    } catch (IllegalArgumentException ex) {
        Log.d(TAG, "network provider does not exist, " + ex.getMessage());
    }
    try {
        mLocationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                mLocationListeners[0]);
        
        SharedPreferences settings = getSharedPreferences("HT",MODE_PRIVATE);
        
        
        
        /*
         * String canStart = "";
        do
        {
        	 canStart = settings.getString("HT_Start","KO");
        	 Log.i(TAG, "Can we start? --> "+ canStart);
        	 Thread.sleep(2000);        	 
        }
        while(canStart != "OK");
        Log.i(TAG, "Starting! =)");
        */
        
        mLocationListeners[0].Email = settings.getString("HT_Email","Not defined");
        mLocationListeners[0].Imei = mTelephoneManager.getDeviceId();
        
    } catch (java.lang.SecurityException ex) {
        Log.i(TAG, "fail to request location update, ignore", ex);
    } catch (IllegalArgumentException ex) {
        Log.d(TAG, "gps provider does not exist " + ex.getMessage());
    } 
}
@Override
public void onDestroy()
{
     Log.e(TAG, "onDestroy");
    super.onDestroy();
    if (mLocationManager != null) {
        for (int i = 0; i < mLocationListeners.length; i++) {
            try {
                mLocationManager.removeUpdates(mLocationListeners[i]);
            } catch (Exception ex) {
                Log.i(TAG, "fail to remove location listners, ignore", ex);
            }
        }
    }
} 
private void initializeLocationManager() {
   Log.e(TAG, "initializeLocationManager");
    if (mLocationManager == null) {
        mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
    }
    if (mTelephoneManager == null)
    {
    	mTelephoneManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    }
}
}
